<?php

namespace App\Models;


use App\Models\Concerns\ScopeFilterable;
use App\Observers\Contract\ObserverCleanable;
use App\Services\Locale\AppLanguage;
use App\Services\Utils\OSSable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

/**
 * Class DevicePreset - 设备预设场景
 *
 * @package App\Models
 */
class DevicePreset extends Model implements ObserverCleanable
{
    use ScopeFilterable,
        OSSable;

    protected $table = 'device_presets';

    protected static $unguarded = true;

    const IS_SHOW = 1;

    protected $casts = [
        'device_id'         => 'int',
        'sort_order'        => 'int',
        'preset'            => 'json',
        'is_show'           => 'int',
        'luminance'         => 'int',
        'color_temperature' => 'int',
    ];

    protected $logo_key_prefix = 'device/preset/logo/';

    public function devicePresetDescriptions(): hasMany
    {
        return $this->hasMany(DevicePresetDescription::class, 'device_preset_id', 'id');
    }

    /**
     * 对应请求的多语言描述
     *
     * @return hasOne
     */
    public function localeDescription(): hasOne
    {
        return $this->hasOne(DevicePresetDescription::class, 'device_preset_id', 'id')
            ->where('language_id', AppLanguage::getLanguageIdFromAppLocale());
    }

    /**
     * @return string|null
     *
     * @throws \OSS\Core\OssException
     */
    public function getLogoAttribute(): ?string
    {
        return $this->attributeToStaticUrl('logo');
    }

    /**
     * @param $data
     *
     * @return string|null
     *
     * @throws \Exception
     */
    public function setLogoAttribute($data)
    {
        if (is_file($data)) {
            $file_key = $this->uploadPostFile($data, $this->logo_key_prefix);
            $this->attributes['logo'] = $file_key;
        } else if (is_string($data) && strlen($data)) {
            $this->attributes['logo'] = $data;
        }
    }

    /**
     * @return array
     */
    public function keyCleanColumns(): array
    {
        return ['logo'];
    }
}
